var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { User, Role } = require('../model/model');
const bcrypt = require('bcryptjs');

// JWT密钥 - 与index.js中保持一致
const JWT_SECRET = 'rbac-system-secret-key';

// 验证Token中间件 - 与index.js中保持一致
const authMiddleware = (req, res, next) => {
  // 获取token
  const token = req.header('x-auth-token');

  // 检查是否有token
  if (!token) {
    return res.status(401).json({ code: 401, message: '无访问权限，请先登录' });
  }

  try {
    // 验证token
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ code: 401, message: '无效的Token' });
  }
};

// 权限检查中间件
const checkPermission = (permission) => {
  return (req, res, next) => {
    // 检查用户是否有权限
    if (req.user.role === '老板' || req.user.permissions.includes('all') || req.user.permissions.includes(permission)) {
      next();
    } else {
      res.status(403).json({ code: 403, message: '权限不足' });
    }
  };
};

// 获取用户列表
router.get('/', authMiddleware, checkPermission('user:view'), async function(req, res) {
  try {
    const { page = 1, limit = 10, username, role } = req.query;
    const skip = (page - 1) * limit;
    
    // 构建查询条件
    let query = {};
    if (username) {
      query.username = { $regex: username, $options: 'i' };
    }
    
    if (role) {
      const roleDoc = await Role.findOne({ name: role });
      if (roleDoc) {
        query.role = roleDoc._id;
      }
    }
    
    // 查询用户总数
    const total = await User.countDocuments(query);
    
    // 查询用户列表
    const users = await User.find(query)
      .populate('role')
      .select('-password')
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createTime: -1 });
    
    // 格式化返回数据
    const formattedUsers = users.map(user => ({
      id: user._id,
      username: user.username,
      email: user.email,
      phone: user.phone,
      sex: user.sex,
      age: user.age,
      role: user.role ? user.role.name : null,
      status: user.status,
      createTime: user.createTime
    }));
    
    res.json({
      code: 200,
      data: {
        total,
        list: formattedUsers,
        page: parseInt(page),
        limit: parseInt(limit),
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({ code: 500, message: '获取用户列表失败', error: error.message });
  }
});

// 获取单个用户信息
router.get('/:id', authMiddleware, checkPermission('user:view'), async function(req, res) {
  try {
    const user = await User.findById(req.params.id).select('-password').populate('role');
    if (!user) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    
    res.json({
      code: 200,
      data: {
        id: user._id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        sex: user.sex,
        age: user.age,
        role: user.role ? user.role.name : null,
        status: user.status,
        createTime: user.createTime
      }
    });
  } catch (error) {
    console.error('获取用户信息失败:', error);
    res.status(500).json({ code: 500, message: '获取用户信息失败', error: error.message });
  }
});

// 更新用户信息
router.put('/:id', authMiddleware, checkPermission('user:edit'), async function(req, res) {
  try {
    const { email, phone, sex, age, roleName, status } = req.body;
    
    // 查找用户
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    
    // 更新角色
    if (roleName) {
      const role = await Role.findOne({ name: roleName });
      if (!role) {
        return res.status(400).json({ code: 400, message: '指定的角色不存在' });
      }
      user.role = role._id;
    }
    
    // 更新其他信息
    if (email) user.email = email;
    if (phone !== undefined) user.phone = phone;
    if (sex !== undefined) user.sex = sex;
    if (age !== undefined) user.age = age;
    if (status !== undefined) user.status = status;
    
    await user.save();
    
    res.json({ code: 200, message: '用户信息更新成功' });
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json({ code: 500, message: '更新用户信息失败', error: error.message });
  }
});

// 更新用户密码
router.put('/:id/password', authMiddleware, async function(req, res) {
  try {
    const { oldPassword, newPassword } = req.body;
    
    // 验证必填字段
    if (!oldPassword || !newPassword) {
      return res.status(400).json({ code: 400, message: '旧密码和新密码为必填项' });
    }
    
    // 只有管理员或本人可以修改密码
    if (req.user.id !== req.params.id && req.user.role !== '老板' && req.user.role !== '管理员') {
      return res.status(403).json({ code: 403, message: '权限不足' });
    }
    
    // 查找用户
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    
    // 验证旧密码
    const isMatch = await bcrypt.compare(oldPassword, user.password);
    if (!isMatch) {
      return res.status(400).json({ code: 400, message: '旧密码错误' });
    }
    
    // 加密新密码
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(newPassword, salt);
    
    await user.save();
    
    res.json({ code: 200, message: '密码更新成功' });
  } catch (error) {
    console.error('更新密码失败:', error);
    res.status(500).json({ code: 500, message: '更新密码失败', error: error.message });
  }
});

// 删除用户
router.delete('/:id', authMiddleware, checkPermission('user:delete'), async function(req, res) {
  try {
    // 查找用户
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json({ code: 404, message: '用户不存在' });
    }
    
    // 不允许删除老板角色的用户
    const role = await Role.findById(user.role);
    if (role && role.name === '老板') {
      return res.status(403).json({ code: 403, message: '不允许删除老板角色的用户' });
    }
    
    await User.findByIdAndDelete(req.params.id);
    
    res.json({ code: 200, message: '用户删除成功' });
  } catch (error) {
    console.error('删除用户失败:', error);
    res.status(500).json({ code: 500, message: '删除用户失败', error: error.message });
  }
});

// 获取所有角色
router.get('/roles/all', authMiddleware, async function(req, res) {
  try {
    const roles = await Role.find();
    res.json({
      code: 200,
      data: roles.map(role => ({
        id: role._id,
        name: role.name,
        description: role.description,
        permissions: role.permissions
      }))
    });
  } catch (error) {
    console.error('获取角色列表失败:', error);
    res.status(500).json({ code: 500, message: '获取角色列表失败', error: error.message });
  }
});

module.exports = router;
